<template>
  <div class="segment-editor-container">
    <div class="editor-header">
      <div class="header-top">
        <div class="title-section">
          <template v-if="isEditing">
            <div class="edit-header">
              <div class="input-group">
                <span class="input-label">文段标题</span>
                <el-input
                  v-model="title"
                  placeholder="请输入文段标题"
                  class="title-input"
                  @input="handleTitleChange"
                />
              </div>
              <div class="input-group">
                <span class="input-label">所属文档</span>
                <el-input
                  v-model="documentTitle"
                  disabled
                  class="document-input"
                />
              </div>
            </div>
          </template>
          <template v-else>
            <h2 class="text-xl font-semibold">{{ title || '未命名文段' }}</h2>
            <p class="document-subtitle">{{ documentTitle }}</p>
          </template>
        </div>
        <div class="action-buttons">
          <el-button 
            @click="$emit('back')"
            class="action-button"
          >
            <el-icon class="el-icon">
              <Back />
            </el-icon>
            返回
          </el-button>
          <el-button 
            type="primary" 
            @click="toggleEditMode"
            class="action-button"
          >
            <el-icon class="el-icon">
              <component :is="isEditing ? Check : Edit" />
            </el-icon>
            {{ isEditing ? '保存' : '编辑' }}
          </el-button>
          <el-button 
            type="warning"
            @click="openMergeDialog"
            class="action-button"
          >
            <el-icon class="el-icon">
              <EditPen />
            </el-icon>
            合并
          </el-button>
          <el-button 
            type="success" 
            @click="handleJiwei"
            class="action-button jiwei-button"
          >
            <el-icon class="el-icon">
              <Medal />
            </el-icon>
            积微
            <span class="jiwei-count" v-if="jiweiCount > 0 && !isMobile">({{ jiweiCount }})</span>
          </el-button>
        </div>
      </div>
      <div class="navigation-buttons" v-if="!isEditing && segmentList.length > 1">
        <el-button 
          @click="goToPrevious"
          class="action-button"
          :disabled="!hasPrevious"
        >
          <el-icon class="el-icon">
            <ArrowLeft />
          </el-icon>
          上一段
        </el-button>
        <div class="page-info">
          <span class="current-page">{{ currentIndex + 1 }}</span>
          <span class="separator">/</span>
          <span class="total-pages">{{ totalSegments }}</span>
        </div>
        <el-button 
          @click="goToNext"
          class="action-button"
          :disabled="!hasNext"
        >
        下一段
        <el-icon class="el-icon">
            <ArrowRight />
          </el-icon>
        </el-button>
      </div>
    </div>

    <div v-if="isEditing" class="editor-wrapper">
      <md-editor 
        ref="editorRef"
        v-model="content" 
        :toolbars="toolbars"
        :prettier="true"
        @save="saveContent"
        class="markdown-editor"
      >
        <template #defToolbars>
          <Mark>
            <template #trigger>
              <el-icon><Brush /></el-icon>
            </template>
          </Mark>
        </template>
      </md-editor>
    </div>
    <div v-else class="preview-wrapper">
      <md-preview :modelValue="content" class="markdown-preview" />
    </div>

    <el-dialog v-model="showMergeDialog" title="选择要合并的文段" width="420px">
      <div style="display: flex; flex-direction: column; gap: 18px;">
        <el-checkbox-group v-model="mergeSelection">
          <div v-if="prevSegment" class="merge-segment-card merge-prev">
            <el-checkbox :label="prevSegment.id" class="merge-checkbox">
              <span class="merge-dot merge-dot-prev"></span>
              <span class="merge-segment-title">上一段：{{ prevSegment.title || '无标题' }}</span>
            </el-checkbox>
          </div>
          <div v-if="nextSegment" class="merge-segment-card merge-next">
            <el-checkbox :label="nextSegment.id" class="merge-checkbox">
              <span class="merge-dot merge-dot-next"></span>
              <span class="merge-segment-title">下一段：{{ nextSegment.title || '无标题' }}</span>
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMergeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleMerge">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { MdEditor, MdPreview, config } from 'md-editor-v3'
import { Mark } from '@vavt/v3-extension'
import MarkExtension from 'markdown-it-mark'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, 
  ArrowRight, 
  Edit, 
  Check, 
  Back, 
  Medal, 
  Brush,
  EditPen
} from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import 'md-editor-v3/lib/preview.css'
import 'md-editor-v3/lib/style.css'
import '@vavt/v3-extension/lib/asset/Mark.css'
import { saveMemory, clockMemory, getDocumentSegments, mergeMemory } from '@/api/document'
import emitter from '@/utils/eventBus'

const props = defineProps({
  segmentData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['save', 'back', 'update'])

const content = ref('')
const title = ref('')
const documentTitle = ref('')
const isEditing = ref(false)
const currentIndex = ref(0)
const segmentList = ref([])
const editorRef = ref(null)
const jiweiCount = ref(0)

const totalSegments = ref(0)
const hasPrevious = computed(() => currentIndex.value > 0)
const hasNext = computed(() => currentIndex.value < segmentList.value.length - 1)
const isMobile = ref(window.innerWidth <= 768)
window.addEventListener('resize', () => {
  isMobile.value = window.innerWidth <= 768
})

onMounted(async () => {
  try {
    await nextTick()
    if (props.segmentData) {
      content.value = props.segmentData.content || ''
      title.value = props.segmentData.title || `文段 ${props.segmentData.order || 1}`
      documentTitle.value = props.segmentData.documentTitle || ''
      segmentList.value = props.segmentData.segmentList || []
      currentIndex.value = props.segmentData.currentIndex || 0
      jiweiCount.value = props.segmentData.readNum || 0
      totalSegments.value = props.segmentData.totalCount || segmentList.value.length
    }
    if (!props.segmentData?.content) {
      isEditing.value = true
      await nextTick()
      if (editorRef.value) {
        editorRef.value.togglePreview(false)
      }
    }
  } catch (error) {
    console.error('组件初始化失败:', error)
    ElMessage.error('初始化失败，请刷新页面重试')
  }
})

config({
  markdownItConfig(md) {
    md.use(MarkExtension)
  }
})

const toolbars = [
  'bold',
  'underline',
  'italic',
  'strikethrough',
  '-',
  'title',
  'quote',
  'unordered-list',
  'ordered-list',
  'preview',
  0,
  '-',
  'code-row',
  'code',
  'link',
  'image',
  'table',
  '-',
  'fullscreen',
  'page-break',
  '-',
  'help'
]

const toggleEditMode = async () => {
  if (isEditing.value) {
    await saveContent()
  } else {
    isEditing.value = true
    await nextTick()
    if (editorRef.value) {
      editorRef.value.togglePreview(false)
    }
  }
  await nextTick()
}

const handleTitleChange = (value) => {
  title.value = value
}

const saveContent = async () => {
  try {
    const saveData = {
      id: props.segmentData?.id,
      title: title.value || '未命名文段',
      content: content.value,
      documentId: props.segmentData?.documentId,
      order: props.segmentData?.order
    }
    await saveMemory(saveData)
    let updatedSegment
    if (props.segmentData?.id) {
      // 更新
      updatedSegment = {
        ...props.segmentData,
        ...saveData
      }
      if (currentIndex.value >= 0 && currentIndex.value < segmentList.value.length) {
        segmentList.value[currentIndex.value] = {
          ...segmentList.value[currentIndex.value],
          ...updatedSegment
        }
      }
    } else {
      // 新建
      updatedSegment = {
        ...saveData,
        id: Date.now(),
        readNum: 0
      }
      segmentList.value.push(updatedSegment)
      currentIndex.value = segmentList.value.length - 1
      totalSegments.value = currentIndex.value + 1
      props.segmentData.id = updatedSegment.id
    }
    isEditing.value = false
    await nextTick()
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

const goToPrevious = async () => {
  if (hasPrevious.value) {
    currentIndex.value--
    const currentSegment = segmentList.value[currentIndex.value]
    content.value = currentSegment.content || ''
    title.value = currentSegment.title || `文段 ${currentSegment.order || currentIndex.value + 1}`
    jiweiCount.value = currentSegment.readNum || 0
    props.segmentData.id = currentSegment.id
    await nextTick()
  }
}

const goToNext = async () => {
  if (hasNext.value) {
    currentIndex.value++
    const currentSegment = segmentList.value[currentIndex.value]
    content.value = currentSegment.content || ''
    title.value = currentSegment.title || `文段 ${currentSegment.order || currentIndex.value + 1}`
    jiweiCount.value = currentSegment.readNum || 0
    props.segmentData.id = currentSegment.id
    await nextTick()
  }
}

const handleJiwei = async () => {
  try {
    const currentSegment = segmentList.value[currentIndex.value]
    if (!currentSegment?.id) {
      ElMessage.warning('请先保存文段后再进行积微')
      return
    }
    const res = await clockMemory(currentSegment.id)
    if (res.data && res.data.data) {
      const { readNum, reward } = res.data.data
      jiweiCount.value = readNum
      // 用id查找并更新segmentList中对应项的readNum
      const idx = segmentList.value.findIndex(seg => seg.id === currentSegment.id)
      if (idx !== -1) {
        segmentList.value[idx] = {
          ...segmentList.value[idx],
          readNum
        }
      }
      if(reward === "很遗憾没有获得积分"){
        ElMessage.warning(reward)
      }else{
        ElMessage({
          type: 'success',
          message: reward,
          duration: 1500
        })
      }
      emitter.emit('refreshHeader')
      if(documentTitle.value){
        const segRes = await getDocumentSegments(documentTitle.value)
        if(segRes.data && Array.isArray(segRes.data.data)){
          segmentList.value = segRes.data.data
          totalSegments.value = segmentList.value.length
          let newIdx = segmentList.value.findIndex(seg => seg.id === currentSegment.id)
          if(newIdx === -1) newIdx = 0
          currentIndex.value = newIdx
          const seg = segmentList.value[newIdx]
          content.value = seg.content || ''
          title.value = seg.title || `文段 ${seg.order || newIdx + 1}`
          jiweiCount.value = seg.readNum || 0
        }
      }
      if (segmentList.value.length > 1) {
        goToNext()
      }
    } else {
      ElMessage.error(res.data?.message || '积微失败')
    }
  } catch (error) {
    console.error('积微失败:', error)
    ElMessage.error('积微失败，请稍后重试')
  }
}

const showMergeDialog = ref(false)
const mergeSelection = ref([])
const prevSegment = computed(() => segmentList.value[currentIndex.value - 1] || null)
const nextSegment = computed(() => segmentList.value[currentIndex.value + 1] || null)

const openMergeDialog = () => {
  mergeSelection.value = []
  showMergeDialog.value = true
}
const handleMerge = async () => {
  if (mergeSelection.value.length === 0) {
    ElMessage.warning('请选择要合并的文段')
    return
  }
  const res = await mergeMemory({
    id: segmentList.value[currentIndex.value]?.id,
    mergeIds: mergeSelection.value
  })
  if (res.data && res.data.success) {
    ElMessage.success('合并成功')
    showMergeDialog.value = false
    // 合并后刷新 segmentList
    if(documentTitle.value){
      const segRes = await getDocumentSegments(documentTitle.value)
      if(segRes.data && Array.isArray(segRes.data.data)){
        segmentList.value = segRes.data.data
        totalSegments.value = segmentList.value.length
        currentIndex.value = 0
        const seg = segmentList.value[0]
        content.value = seg.content || ''
        title.value = seg.title || `文段 ${seg.order || 1}`
        jiweiCount.value = seg.readNum || 0
      }
    }
  } else {
    ElMessage.error('合并失败')
  }
}
</script>

<style scoped>
.segment-editor-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .segment-editor-container {
    padding: 16px;
  }
}

.editor-header {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
  margin-right: 24px;
  position: relative;
}

.title-input,
.document-input {
  width: 100%;
}

.title-input :deep(.el-input__wrapper),
.document-input :deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 12px;
  height: 32px;
  line-height: 32px;
}

.title-input :deep(.el-input__inner),
.document-input :deep(.el-input__inner) {
  font-size: 14px;
  font-weight: 500;
  height: 32px;
  line-height: 32px;
  color: #1a1a1a;
}

.title-input :deep(.el-input__wrapper.is-focus),
.document-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 1px #409EFF !important;
}

.title-input :deep(.el-input__inner)::placeholder {
  color: #909399;
  opacity: 0.7;
}

.document-input :deep(.el-input__inner) {
  color: #909399;
  background-color: #f5f7fa;
}

h2.text-xl {
  font-size: 1.75rem;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
  padding: 8px 0;
  position: relative;
  display: inline-block;
}

h2.text-xl::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, transparent);
  opacity: 0.5;
}

.document-subtitle {
  color: #909399;
  font-size: 14px;
  margin: 4px 0 0 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.navigation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-top: 16px;
}

.action-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  height: 32px;
  line-height: 1;
}

.action-button:hover:not(.is-disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-button .el-icon {
  font-size: 16px;
  display: flex;
  align-items: center;
}

.action-button span {
  display: inline-flex;
  align-items: center;
  line-height: 1;
}

.page-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #fff;
  border-radius: 8px;
  font-weight: 500;
  color: #1a1a1a;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.current-page {
  color: #409EFF;
  font-size: 1.1em;
}

.separator {
  color: #dcdfe6;
}

.total-pages {
  color: #909399;
}

@media (max-width: 768px) {
  .editor-header {
    padding: 16px;
    gap: 12px;
  }

  .header-top {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .title-section {
    margin-right: 0;
    width: 100%;
  }

  .title-input :deep(.el-input__inner) {
    font-size: 1.5rem;
    height: 48px;
  }

  h2.text-xl {
    font-size: 1.5rem;
  }

  .action-buttons {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .action-button {
    flex: 1;
    min-width: 0;
    padding: 6px 12px;
    font-size: 0.9em;
    justify-content: center;
  }

  .action-button .el-icon {
    font-size: 14px;
  }

  .action-button span {
    display: none;
  }

  .jiwei-count {
    display: none;
  }

  .navigation-buttons {
    padding: 8px;
    gap: 12px;
  }

  .page-info {
    padding: 6px 12px;
    font-size: 0.9em;
  }
}

.editor-wrapper {
  flex: 1;
  min-height: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
}

.preview-wrapper {
  flex: 1;
  min-height: 0;
  padding: 32px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow-y: auto;
}

@media (max-width: 768px) {
  .preview-wrapper {
    padding: 16px;
  }
}

.markdown-editor {
  height: 100%;
  flex: 1;
}

.markdown-preview {
  font-size: 16px;
  line-height: 1.8;
  color: #2c3e50;
}

:deep(.md-editor) {
  border: none;
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.md-editor-toolbar) {
  border-bottom: 1px solid #ebeef5;
  padding: 8px 16px;
  flex-shrink: 0;
  overflow-x: auto;
  white-space: nowrap;
}

@media (max-width: 768px) {
  :deep(.md-editor-toolbar) {
    padding: 8px;
  }

  :deep(.md-editor-toolbar-item) {
    padding: 4px 6px;
  }
}

:deep(.md-editor-content) {
  padding: 16px;
  flex: 1;
  overflow-y: auto;
}

@media (max-width: 768px) {
  :deep(.md-editor-content) {
    padding: 12px;
  }
}

:deep(.md-editor-input) {
  height: 100%;
  min-height: 500px;
}

@media (max-width: 768px) {
  :deep(.md-editor-input),
  :deep(.md-editor-preview) {
    min-height: 300px;
  }
}

:deep(.md-editor-preview) {
  height: 100%;
  min-height: 500px;
  overflow-y: auto;
}

:deep(.md-preview) {
  padding: 0;
}

:deep(.md-preview h1) { font-size: 1.8rem; }
:deep(.md-preview h2) { font-size: 1.5rem; }
:deep(.md-preview h3) { font-size: 1.3rem; }
:deep(.md-preview h4) { font-size: 1.2rem; }
:deep(.md-preview h5) { font-size: 1.1rem; }
:deep(.md-preview h6) { font-size: 1rem; }

@media (max-width: 768px) {
  :deep(.md-preview h1) { font-size: 1.5rem; }
  :deep(.md-preview h2) { font-size: 1.3rem; }
  :deep(.md-preview h3) { font-size: 1.2rem; }
  :deep(.md-preview h4) { font-size: 1.1rem; }
  :deep(.md-preview h5) { font-size: 1rem; }
  :deep(.md-preview h6) { font-size: 0.9rem; }
}

:deep(.md-preview p) {
  margin-bottom: 16px;
  line-height: 1.8;
}

:deep(.md-preview code) {
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Fira Code', monospace;
}

:deep(.md-preview pre) {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
  overflow-x: auto;
}

:deep(.md-preview blockquote) {
  border-left: 4px solid #409EFF;
  padding: 8px 16px;
  margin: 16px 0;
  background-color: #f5f7fa;
  border-radius: 0 8px 8px 0;
}

@media (max-width: 768px) {
  :deep(.md-preview pre),
  :deep(.md-preview blockquote) {
    padding: 12px;
    margin: 12px 0;
  }
}

.jiwei-button {
  background-color: #67c23a;
  border-color: #67c23a;
}

.jiwei-button:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.jiwei-count {
  margin-left: 2px;
  font-size: 0.9em;
  opacity: 0.9;
  display: inline-flex;
  align-items: center;
}

@media (max-width: 768px) {
  .jiwei-count {
    display: none;
  }
}

.edit-header {
  display: flex;
  gap: 24px;
  align-items: flex-start;
  width: 100%;
}

.input-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 0;
}

.input-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

@media (max-width: 768px) {
  .edit-header {
    flex-direction: column;
    gap: 16px;
  }

  .input-group {
    width: 100%;
  }
}

.merge-segment-card {
  background: #fff;
  border: 1.5px solid #e4e7ed;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.07);
  padding: 12px 18px;
  display: flex;
  align-items: center;
  transition: box-shadow 0.2s, border-color 0.2s;
  margin-bottom: 0;
}
.merge-segment-card:hover {
  box-shadow: 0 4px 16px rgba(64,158,255,0.13);
  border-color: #409EFF;
}
.merge-checkbox {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 15px;
  font-weight: 500;
}
.merge-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 6px;
}
.merge-dot-prev {
  background: linear-gradient(135deg, #67c23a 60%, #b7eb8f 100%);
}
.merge-dot-next {
  background: linear-gradient(135deg, #409EFF 60%, #a0cfff 100%);
}
.merge-segment-title {
  font-weight: 600;
  color: #222;
  font-size: 15px;
}
</style> 